var crc = require('crc');
var plog = require('./plog');
var moment = require('moment');

//通用函数， 这个函数最好还是在封装一下吧 
// select an item from list based on key
module.exports.dispatch = function(key, list) {
	var index = Math.abs(crc.crc32(key)) % list.length;
	return list[index];
};
//检查对象是否为空
function isEmpty(v) {
    switch (typeof v) {
    case 'undefined':
        return 0;
    case 'string':
        if (v.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return 0;
        break;
    case 'boolean':
        if (!v) return 0;
        break;
    case 'number':
        if (0 === v || isNaN(v)) return 0;
        break;
    case 'object':
        if (null === v || v.length === 0) return 0;
        for (var i in v) {
            return 1;
        }
        return 0;
    }
    return 0;
}
module.exports.isEmpty = isEmpty;
//另外一个检查对象为空的函数
function isEmpObj(obj){
    if(obj == null) return 0;
    for(var n in obj){return 1} 
    return 0; 
} 
module.exports.isEmpObj = isEmpObj;

//求 array的元素个数 
module.exports.arraycount = function(ar)
{
	var count = 0; 
	for(var k in ar)
	{
		count ++;
	}
	return count;
}
//随机数字的函数， 
//有可能等于最小值， 不可能等于最大值
function GetRandomNum (Min,Max)
{   
	var Range = parseInt(Max) - parseInt(Min);   
	var Rand = Math.random();   
	return(parseInt(Min) + Math.floor(Rand * Range));   
}   ;
module.exports.GetRandomNum = GetRandomNum; 


function ArrayHasVal(arr, val)
{
	for(var i = 0; i < arr.length; i ++)
	{
		if(arr[i] == val) return 0;
	}
	return 1;
}
//取得多个不重复的随机数 
function GetRandomNums (Min, Max, Count)
{
	var c = Max - Min;
	if(c > Count) 
		c = Count;
	var ret = new Array();
	nc = 0; 
	while (nc < c)
	{
		var cval = GetRandomNum(Min, Max);
		if(ArrayHasVal(ret, cval) != 0)
		{
			ret[nc] = cval;
			nc ++;
		}
	}
	return ret;
}
module.exports.GetRandomNums = GetRandomNums; 

//获得 随机物品 
//format is  randnum, xxx,xxx,xxx;
var RandItem = module.exports.RandItem = function(_itemstr)
{
	//plog.out("rand str is " + _itemstr);
	var ar = _itemstr.split(";");
	var sum = 0; 
	for(var i = 0; i < ar.length; i ++)
	{
		var onestr = ar[i];
		if(onestr.split(",").length > 2)
		{
			var rn = parseInt(onestr.split(",")[0]);
			//plog.out("level num is " + sum);
			sum += rn;
		}
	}

	var rrn = GetRandomNum(0, sum);
	//plog.out("rand number is " + rrn);

	var ss = 0; 
	for (var i = 0; i < ar.length; i ++)
	{
		var onestr = ar[i];
		var rn = parseInt(onestr.split(",")[0]);
		ss += rn;
		if (rrn < ss)
		{
	//		plog.out("reward str is " + onestr);
			return onestr;		
		}
	}
	return "";

}
/*
var tt = "14,0,72,1;14,0,80,1;14,0,88,1;14,0,96,1;14,0,104,1;14,0,112,1;14,0,120,1;7,2,1,1;5,2,1,2;7,2,2,1;5,2,2,2;7,2,3,1;5,2,3,2;7,2,4,1;5,2,4,2;14,0,73,1;14,0,81,1;14,0,89,1;14,0,97,1;14,0,105,1;14,0,113,1;14,0,121,1;854,0,38,1";
plog.out(RandItem(tt));
plog.out(RandItem(tt));
plog.out(RandItem(tt));
plog.out(RandItem(tt));*/
module.exports.RemoveRandNum = function(_itemstr)
{
	plog.out("RemoveRandNum string " + _itemstr);
	//_itemstr = "" + _itemstr;
	var index = _itemstr.indexOf(",");
	var st = _itemstr.substr(index+1);
	return st; 
}
//clone 一个对象 切记不要有死循环
function Clone(myObj){
	if(typeof(myObj) != 'object') return myObj;
	if(myObj == null) return myObj;
	var myNewObj = new Object();
	for(var i in myObj)
	myNewObj[i] = Clone(myObj[i]);
	return myNewObj;
}
module.exports.Clone = Clone; 

//获得一个随机字符串
function RandString(_len)
{
	var ret = "";
	for(var i = 0; i < _len; i ++ )
	{
		var n = GetRandomNum(0, 10); 
		ret = ret + "" + n;
	}
	return ret; 
}
module.exports.RandString = RandString; 

// Get member count of array
function ArrayLength(_a) {
	var i = 0; 
	for(k in _a)
	{
		i++;
	}
	return i;
}
module.exports.ArrayLength = ArrayLength;

//获取array 里面一个不存在的key
module.exports.arraynewkey = function(ar)
{
	while(true)
	{
		var r = GetRandomNum(0, 1000000);
		if(r in ar) 
		{} else {
			return r;
		}
	}
}

//给集合增加一个对象
module.exports.arrayappend = function(ar, val)
{
	var key = this.arraynewkey(ar);
	ar[key] = val;
}

module.exports.str2obj = function(_str)
{
	try{
		if(_str == null) return {};
		if(_str == "")
			return {};
		else 
			return JSON.parse(_str);
	} catch (err) {  
  		plog.error('Fuck JSON ERROR: ' + _str);  
		return {};
	}
};

module.exports.obj2str = function(_obj)
{
	if(isEmpObj(_obj) == 0)
		return "{}";
	return JSON.stringify(_obj);
};


//当前unix 时间
var now = module.exports.now = function()
{
	return Math.round((new Date()).getTime() / 1000);
};

//当日零时unix时间
var ZeroTime = module.exports.ZeroTime = function()
{
	var today = new Date();
	today.setHours(0);
	today.setMinutes(0);
	today.setSeconds(0);
	today.setMilliseconds(0);

	return Math.round(today.getTime() / 1000);
};


var nextTimeofDay = module.exports.nextTimeofDay = function(_t)
{
	var st = ZeroTime();
	var n = now();
	st = st + _t; 
	if (n > st) st = st + (60 * 60 * 24);
	return st;
}
var GetDateStr = module.exports.GetDateStr = function(_time)
{
	return moment(_time * 1000).format("YYYYMMDD");
}
function GetMonth(_time)
{
	return parseInt(moment(_time *1000).format("MM"));
}
module.exports.GetMonth = GetMonth;

function GetDay(_time)
{
	return parseInt(moment(_time *1000).format("DD"));
}
module.exports.GetDay = GetDay;

function GetYear(_time)
{
	return parseInt(moment(_time *1000).format("YYYY"));
}
module.exports.GetYear = GetYear;

//获得两个时间戳之间的日期差异 
module.exports.dayfrom = function(_ntime, _otime)
{
	var n = moment([GetYear(_ntime), GetMonth(_ntime), GetDay(_ntime)]);
	var o = moment([GetYear(_otime), GetMonth(_otime), GetDay(_otime)]);
	return n.diff(o, 'days')
	
}

module.exports.GetDayOfWeek = function(_time)
{
	return parseInt(moment(_time *1000).format("E"));	
}

/*
module.exports.GetTimeofStartDay = function(_time)
{
	return 0;
}*/
/*
module.exports.nowfromyear = function()
{
	return 300;
};
module.exports.nowfrommonth = function()
{
	return 300;
};
module.exports.nowfromweek = function()
{
	return 300;
};
module.exports.nowfromday = function()
{
	return 300;
};
*/

//=============================================================================
//Dump 一个数据对象， 但是切记， 不能有引用循环， 否则， 这个函数， 无法退出。。。 死循环
function objdump(arr){
	var str = "";
	for(var key in arr){
		if(typeof(arr[key])=='array'||typeof(arr[key])=='object'){//递归调用  
			str+= objdump(arr[key]);
		}else{
			str += (key + ' = ' + arr[key] + '\n');
		}
	}
	return str;
}
module.exports.objdump = objdump;


module.exports.str2int = function(_str)
{
	var i = parseInt(_str);
	if(isNaN(i)) return 0;
	if(i == null)
		i = 0; 
	return parseInt(i);
}
